from .fingerprint_interface import FingerprintDatabase
#

class TemporalFingerprint:
    timestamp = 0
    index = 0
    rssi = 0

    def __init__(self, raw_data, fp_database):
        if type(fp_database) != FingerprintDatabase:
            raise TypeError('database is not fingerprint_database')
        datas = raw_data.split(' ')
        self.timestamp = int(datas[0])
        self.index = fp_database.get_index(datas[1])
        self.rssi = float(datas[2][:-1])

    def __str__(self):
        if self.index != None:
            return '{} {} {}\n'.format(self.timestamp, self.index, self.rssi)
        else:
            return '{} unknown {}\n'.format(self.timestamp, self.rssi)


class TemporalFingerprintSeq:
    tem_fp = []
    apList = []

    def __init__(self, file_dir, fp_database):
        if type(fp_database) != FingerprintDatabase:
            raise TypeError('database is not fingerprint_database')
        self.apList = fp_database.apList
        in_file = open(file_dir + '\\ble.txt', 'r')
        lines = in_file.readlines()
        for line in lines:
            tmp = TemporalFingerprint(line, fp_database)
            if tmp.index != None:
                self.tem_fp.append(tmp)

    def __str__(self):
        out_string = ''
        for fp in self.tem_fp:
            if fp.index != None:
                out_string = out_string + '{} {} {}\n'.format(fp.timestamp, self.apList[fp.index], fp.rssi)
            else:
                out_string = out_string + '{} unknown {}\n'.format(fp.timestamp, fp.rssi)
        return out_string

    def find_next(self, timestamp):
        if self.tem_fp[0].timestamp >= timestamp:
            return self.tem_fp[0]
        if self.tem_fp[-1].timestamp < timestamp:
            return self.tem_fp[-1]
        st = 0
        en = len(self.tem_fp) - 1
        while (st + 1 < en):
            mid = int((st + en) / 2)
            if (self.tem_fp[mid].timestamp >= timestamp):
                en = mid
            else:
                st = mid
        return self.tem_fp[en]

    def find_all(self, timestamp, MAX_TOLERATE_TIME_DELTA):
        l = len(self.apList)
        result = [None for i in range(l)]
        ll = len(self.tem_fp)
        for i in range(ll):
            if self.tem_fp[i].timestamp <= timestamp and self.tem_fp[i].timestamp >= timestamp - MAX_TOLERATE_TIME_DELTA:
                result[self.tem_fp[i].index] = self.tem_fp[i].rssi
        return result

